package com.fxu.gen.dubbo;

import cn.hutool.core.util.StrUtil;
import com.fxu.framework.core.base.Constant;
import com.fxu.framework.core.base.Result;
import com.fxu.framework.core.enums.StatusEnum;
import com.fxu.gen.AutoUtil;
import com.fxu.gen.Base;
import com.fxu.gen.StrBuf;
import com.fxu.gen.enums.SignEnum;
import com.fxu.gen.enums.TplEnum;
import com.fxu.tpl.entity.Column;
import com.fxu.tpl.entity.Table;
import com.fxu.tpl.enums.ProjectTypeEnum;
import org.springframework.util.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * RestImpl类的模板替换
 * @author fangxu
 */
public final class RestImpl extends Base {
	public RestImpl(Table table, File destFile) {
		super(table, TplEnum.RestImpl, destFile);
	}
	
	@Override
    public String doReplace() {
		if (Objects.equals(project.getType(), ProjectTypeEnum.SPRING_BOOT.code())) {
			fileTxt = fileTxt.replace("import com.learned.tpl.facade.feign.ApiCloudFeign;", "import com.learned.core.base.cloud.ApiBaseServiceImpl;");
			fileTxt = fileTxt.replace("private ApiCloudFeign apiCloudFeign;", "private ApiBaseServiceImpl api"+StrUtil.upperFirst(table.getModule().getName())+"Feign;");
		}
		String fileTxt = super.doReplace();
		fileTxt = replace(fileTxt, SignEnum.ClassAuto, getSaveBefore().append(getFillBeans()));
		fileTxt = replaceImports(fileTxt, false); //放最后才能收集imports
		return fileTxt;
	}
	
	private StringBuffer getSaveBefore() {
		StringBuffer buffer = new StringBuffer();
		
		String newTxt = fileTxt;
		newTxt = replace(newTxt, SignEnum.ClassAuto, new StringBuffer());
		String method = "public Result<" + tableBean + "> saveBefore(" + tableBean + " dbBean, " + tableBean + " bean) {";
		if (!newTxt.contains(method)) {
			buffer.append("	@Override\n");
			buffer.append("	").append(method).append("\n");
			buffer.append("		if (bean != null) {\n");
			buffer.append("			if (dbBean == null) { // 添加\n");
			String priKeyName = getPriKeyClnName(columns);
			for (Column column : columns) {
				if (column.getName().equals(priKeyName)) {
					continue;
				}
				String limits, defVal = null;
				if (!StrUtil.isEmpty(column.getLimits())) {
					limits = column.getLimits();
					// 默认第一个
					if (limits.contains(":")) {
						defVal = limits.substring(0, limits.indexOf(":"));
					} else if (limits.contains(",")) {
						defVal = limits.substring(0, limits.indexOf(","));
					}
				}
				if (column.isString()) {
					defVal = "\"" + (defVal == null ? "" : defVal) + "\"";
				}
				// 数据库not null, 前端添加允许null, 那么必须在业务逻辑初始化
				// !isTrue(column.getRequired()) || !isTrue(column.getFormShow())
				if (isTrue(column.getNotNull()) && !isTrue(column.getRequired()) && StrUtil.isEmpty(column.getDefVal())) {
					if (!column.getName().equals(Constant.CLN_VERSION) && !column.getName().equals(Constant.CLN_STATUS)) {
						String tmpDefVal = defVal == null ? getDefVal(column) : defVal;
						AutoUtil.toImports(imports, column.isDecimal() ? BigDecimal.class : null);
						AutoUtil.toImports(imports, column.isDate() ? Date.class : null);
						AutoUtil.toImports(imports, column.isFloat() ? Float.class : null);
						AutoUtil.toImports(imports, column.isDouble() ? Double.class : null);
						buffer.append("				if (bean.get"+AutoUtil.getBean(column.getName())+"() == null) {\n");
						buffer.append("					bean.set"+AutoUtil.getBean(column.getName())+"("+tmpDefVal+");\n");
						buffer.append("				}\n");
					} else if (column.getName().equals(Constant.CLN_STATUS)) {
						buffer.append("				if (bean.getStatus() == null) {\n");
						buffer.append("					bean.setStatus(StatusEnum.SHOW.code());\n");
						buffer.append("				}\n");
//						AutoUtil.toImports(imports, "com."+destProject+".core.enums.StatusEnum");
						AutoUtil.toImports(imports, StatusEnum.class);
					}
				}
			}
			buffer.append("			} else { // 更新\n");
			String[] array = {};
			for (Column column : columns) {
				if (Constant.CLN_STATUS.equals(column.getName())) {
					buffer.append("				// 不能跨级更新状态\n");
					List<String> limitList = new ArrayList<>();
					if (!StrUtil.isEmpty(column.getLimits())) {
						if (column.getLimits().contains(":")) {
							array = column.getLimits().split(",");
						}
						for (String a : array) {
							a = a.substring(0, a.indexOf(":"));
							if (!"0".equals(a)) {
								limitList.add(a);
							}
						}
					}
					if (limitList.size() > 0) {
						String columnBean = AutoUtil.getBean(column.getName());
						buffer.append("				if (bean.get"+columnBean+"() != null && dbBean.get"+columnBean+"() != null && !bean.get"+columnBean+"().equals(dbBean.get"+columnBean+"())) {\n");
						for (int i = 1; i < limitList.size(); i ++) {
							buffer.append("					if (bean.get"+columnBean+"() == "+limitList.get(i)+" && dbBean.get"+columnBean+"() != "+limitList.get(i-1)+") {\n");
							buffer.append("						return Result.error(\"修改的字段值错误!dbBean.get"+columnBean+"=\" + dbBean.get"+columnBean+"());\n");
							buffer.append("					}\n");
						}
						buffer.append("				}\n");
					}
				}
			}
			buffer.append("			}\n");
			buffer.append("		}\n");
			buffer.append("		return super.saveBefore(dbBean, bean);\n");
			buffer.append("	}\n");
			
			AutoUtil.toImports(imports, Result.class);
		}
		
		return buffer;
	}
	
	private String getFillBean() {
		StrBuf buffer = new StrBuf();
		String newTxt = fileTxt;
		newTxt = replace(newTxt, SignEnum.RestServiceImplAuto, new StringBuffer());
		String mtd = "public void fillBean(" + tableBean + " bean, List<String> showFlags) {";
		if (!newTxt.contains(mtd)) {
			AutoUtil.toImports(imports, List.class);

			buffer.append(1, "");
			buffer.append(1, "@Override");
			buffer.append(1, mtd);
			buffer.append(2, "// 按需要填充数据");
			buffer.append(1, "}");
		}
		return buffer.toString();
	}

	private String getFillBeans() {
		StrBuf buffer = new StrBuf();
		String newTxt = fileTxt;
		newTxt = replace(newTxt, SignEnum.RestServiceImplAuto, new StringBuffer());
		String mtd = "public void fillBeans(List<" + tableBean + "> beans, List<String> showFlags) {";
		if (!newTxt.contains(mtd)) {
			AutoUtil.toImports(imports, List.class);

			buffer.append(1, "");
			buffer.append(1, "@Override");
			buffer.append(1, mtd);
			buffer.append(2, "// 按需要填充数据");
			buffer.append(1, "}");
		}
		return buffer.toString();
	}
	
	private static String getDefVal(Column column) {
		if (column == null) {
			return "";
		}
		if (column.isString()) {
			return "\"\"";
		} else if (column.isDate()) {
			return "new Date()";
		} else if (column.isLong()) {
			return "0L";
		} else if (column.isInteger()) {
        	return "0";
        } else if (column.isDecimal()) {
        	return "BigDecimal.ZERO";
        } else if (column.isBoolean()) {
        	return "false";
        } else if (column.isFloat()) {
        	return "0F";
        } else if (column.isDouble()) {
        	return "0D";
        } else {
        	System.out.println("RestImpl.getDefVal["+column.getName()+"]===>找不到类型!" + column);
        }
		return "";
    }
}
